const {promisify}=require('util')
const path=require('path')

const download=promisify(require('download-git-repo'))
const open=require('open')

const {vueRepo}=require('../config/repo-config')
const {commandSpawn}=require('../utils/terminal')
const {
  compile,
  writeToFile,
  mkdirSync
}=require('../utils/utils')

const createProjectAction=async(project)=>{
  console.log("hinus helps you create your project~")
  //1.clone项目
  await download(vueRepo,project,{clone:true})
  //2.执行npm install
  const command=process.platform==='win32'?'npm.cmd':'npm'
  await commandSpawn(command,['install'],{cwd:`./${project}`})
  //3.执行npm run serve
  commandSpawn(command,['run','serve'],{cwd:`./${project}`})
  //4.打开浏览器
  open('http://localhost:8080/')
}

const addCpnAction=async(name,dest)=>{
  //1.编译ejs模板result
  const result=await compile('vue-component.ejs',{name,lowerName:name.toLowerCase()})
  //2.将result写入到.vue文件中
  if(mkdirSync(dest)){
    const targetPath=path.resolve(dest,`${name}.vue`)
    writeToFile(targetPath,result)
  }
}

const addPage=async(name,dest)=>{
  const data={name,lowerName:name.toLowerCase()}

  const pageResult=await compile('vue-component.ejs',data)
  const routeResult=await compile('vue-router.ejs',data)

  if(mkdirSync(dest)){
    const targetPagePath=path.resolve(dest,`${name}.vue`)
    const targetRoutePath=path.resolve(dest,'route.js')
    writeToFile(targetPagePath,pageResult)
    writeToFile(targetRoutePath,routeResult)
  }
}

const addStore=async(name,dest)=>{
  const storeResult=await compile('vue-store.ejs',{})
  const typesResult=await compile('vue-types.ejs',{})
  if(mkdirSync(dest)){
    const targetStorePath=path.resolve(dest,`${name}.js`)
    const targetTypesPath=path.resolve(dest,'types.js')
    writeToFile(targetStorePath,storeResult)
    writeToFile(targetTypesPath,typesResult)
  }
}

module.exports={
  createProjectAction,
  addCpnAction,
  addPage,
  addStore
}